package com.alt.manager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;

import com.alt.base.ALTBaseActivity;
import com.alt.base.ALTMainForm;
import com.alt.connector.RestClient;
import com.alt.handler.BaseCmdHandler;
import com.alt.manager.ALTPTCMgr.ALERT_OPTION;
import com.alt.manager.ALTPTCMgr.COMMAND_TYPE;
import com.alt.manager.ALTPTCMgr.CONFIRM_DIALOG_ID;
import com.alt.manager.ALTPTCMgr.SCREEN_UI;
import com.alt.models.AdsInfo;
import com.alt.models.UserData;
import com.alt.models.UserLogInfo;
import com.alt.shared.CommandAsyncTask;
import com.alt.shared.IServiceCommandResult;
import com.alt.shared.ALTSharedMgr;
import com.alt.utils.ALTSysUtils;

public class ALTAppMgr {
	//back press
	public static boolean isBack=false;
	public static boolean isChangeAvarta=false;
	public static boolean isLoginFace=false;
	public static boolean isStillLogin=false;
	
	// Class Member
	public ALTBaseActivity m_Activity = null;
	public ALTMainForm m_MainForm = null;

	public ALTSharedMgr m_SharedMgr = null;
	public ALTSoundMgr m_SoundMgr = null;

	public SCREEN_UI m_CurScreenMode = SCREEN_UI.NONE;
	public SCREEN_UI m_PrevScreenMode = SCREEN_UI.NONE;

	// UserData
	public UserData m_UserData = null;
	
	//Temporary user data information
	public UserLogInfo m_UserLogInfo = null;
	
	//Temporary Advertisement List
	public List<AdsInfo> m_AdsLst = null;

	// data for new
	public boolean m_allow2loadmore = false;


	/**
	 * Login or not
	 */
	public boolean m_LoggedIn = false;

	// Current Tab Name
	public String m_SelectTabName = ALTMainForm.TAG_TAB_HOME;

	// Activity <-> AppMgr Share
	public static ALTAppMgr g_AppMgr = null;

	public static ALTAppMgr getInstance(ALTBaseActivity _Activity) {
		if (g_AppMgr == null) {
			// getSystemService
			g_AppMgr = new ALTAppMgr();
			g_AppMgr.initApp();
		}

		// set current activity
		g_AppMgr.setActivity(_Activity);
		return g_AppMgr;
	}

	public static ALTAppMgr getInstance() {

		if (g_AppMgr == null) {
			// getSystemService
			g_AppMgr = new ALTAppMgr();
			g_AppMgr.initApp();
		}

		return g_AppMgr;
	}

	/**
	 * 
	 * @param subUrl
	 * @return
	 */
	public static String makeWebMobileUrl(String subUrl) {
		StringBuilder sb = new StringBuilder();
		sb.append("http://");
		sb.append(RestClient.SVC_SERVER_IP);
		sb.append(":");
		sb.append(RestClient.MWEB_PORT);

		if (!subUrl.startsWith("/")) {
			sb.append("/");
		}

		sb.append(subUrl);

		return sb.toString();
	}

	// Initialization Application
	public void initApp() {
		// instance
		if (m_SharedMgr == null)
			m_SharedMgr = new ALTSharedMgr();

		if (m_SoundMgr == null) {
			m_SoundMgr = new ALTSoundMgr();
		}

		m_UserData = new UserData();
		m_UserLogInfo = new UserLogInfo();	
		
		m_AdsLst = new ArrayList<AdsInfo>();
	}

	// set data for current user
	public void setUserData(UserData userdata) {
		m_UserData = userdata;
		m_UserData.save();
	}

	public UserData getUserdata() {
		return m_UserData;
	}
	
	public void setAllow2Loadmore(boolean value){
		m_allow2loadmore = value;
	}
	
	public boolean getAllow2Loadmore(){
		return m_allow2loadmore;
	}
	
	// set data for current advertisements
	public void setAdsLstData(List<AdsInfo> ads) {
		m_AdsLst = new ArrayList<AdsInfo>();
		m_AdsLst = ads;
		//m_AdsLst.save();
	}

	public List<AdsInfo> getAdsLstData() {
		return m_AdsLst;
	}
	
	// set data for current user
	public void setUserLogInfo(UserLogInfo userLogInfo) {
		m_UserLogInfo = userLogInfo;
		m_UserLogInfo.save();
	}

	public UserLogInfo getUserLogInfo() {
		return m_UserLogInfo;
	}

	// Using Activity Set
	public void setActivity(ALTBaseActivity _Activity) {
		// On changed event
		if (m_Activity != null) {
			m_Activity.onScreenChanged(this.m_PrevScreenMode);
		}

		m_Activity = _Activity;
	}

	/**
	 * process command already
	 */
	public void onCommandReceiveProcessed() {
		if (m_Activity != null) {
			m_Activity.hideProgressDialog();
		}
	}

	public void setMainForm(ALTMainForm _MainForm) {
		m_MainForm = _MainForm;
	}

	// Change ScreenMode Set
	public void setScreenMode(SCREEN_UI newScreenMode) {
		if (m_CurScreenMode != newScreenMode) {
			Log("setScreenMode", "PrevScreen : " + m_CurScreenMode
					+ ", CurScreen : " + newScreenMode);

			m_PrevScreenMode = m_CurScreenMode;
			m_CurScreenMode = newScreenMode;
		}
	}

	// Destroy Application
	public void destroyApp() {
		if (m_SharedMgr != null)
			m_SharedMgr = null;

		if (m_SoundMgr != null) {
			m_SoundMgr = null;
		}

		ALTSysUtils.processKill(m_Activity);
		m_Activity.finish();
	}

	public void setSharedData(Context context) {
		m_SharedMgr.setContext(context);
	}

	// Debug Log Message
	public void viewError(ALTPTCMgr.ERROR errorCode) {
		if (m_Activity != null && m_Activity.m_hViewEvent != null) {
			Message Msg = m_Activity.m_hViewEvent.obtainMessage();
			Msg.what = ALTPTCMgr.VIEW_EVENT_ERROR;
			Msg.obj = errorCode;
			m_Activity.m_hViewEvent.sendMessage(Msg);

			Log.e("ShowLog", "ErrorCode : " + errorCode.ordinal());
		}
	}

	public void viewToast(String msg) {
		if (m_Activity != null && m_Activity.m_hViewEvent != null) {
			Message Msg = m_Activity.m_hViewEvent.obtainMessage();
			Msg.what = ALTPTCMgr.VIEW_EVENT_TOAST;
			Msg.obj = msg;
			m_Activity.m_hViewEvent.sendMessage(Msg);
		}
	}

	public void viewAlert(String msg, ALERT_OPTION option) {
		if (m_Activity != null && m_Activity.m_hViewEvent != null) {
			Message Msg = m_Activity.m_hViewEvent.obtainMessage();
			Msg.what = ALTPTCMgr.VIEW_EVENT_ALERT;
			Msg.arg1 = option.ordinal();
			Msg.obj = msg;
			m_Activity.m_hViewEvent.sendMessage(Msg);
		}
	}

	public void viewConfirmation(CONFIRM_DIALOG_ID dialogId, String msg) {
		if (m_Activity != null && m_Activity.m_hViewEvent != null) {
			Message Msg = m_Activity.m_hViewEvent.obtainMessage();
			Msg.what = ALTPTCMgr.VIEW_EVENT_CONFIRMATION;
			Msg.arg1 = dialogId.ordinal();
			Msg.obj = msg;
			m_Activity.m_hViewEvent.sendMessage(Msg);
		}
	}

	public void viewNotification(String tickerText, String contentTitle,
			String contentText) {
		if (m_Activity != null) {
			m_Activity.onNotification(tickerText, contentTitle, contentText);
		}
	}

	public void viewErrClosing() {
	}

	public void onEventReceiver(SCREEN_UI nextScreenMode) {
		if (m_Activity != null) {
			m_Activity.onEventReceiver(nextScreenMode);
		}
	}

	public void onEventReceiver(SCREEN_UI nextScreenMode, Bundle sendData) {
		if (m_Activity != null) {
			m_Activity.onEventReceiver(nextScreenMode, sendData);
		}
	}

	public void onEventReceiver(COMMAND_TYPE commandType, Bundle cmdData) {
		if (m_Activity != null) {
			m_Activity.onEventReceiver(commandType, cmdData);
		}
	}

	public void sendRecvEvent(int command, Object obj) {
		if (m_Activity != null && m_Activity.m_hRecvDataEvent != null) {
			Message Msg = m_Activity.m_hRecvDataEvent.obtainMessage();
			Msg.what = command;
			Msg.obj = obj;
			m_Activity.m_hRecvDataEvent.sendMessage(Msg);
		}
	}

	public void startServiceCmd(int command, BaseCmdHandler handler,
			Bundle cmdData,boolean showProgress) {
		startServiceCmd(command, m_Activity, handler, cmdData,showProgress);
	}

	public void startServiceCmd(int command, IServiceCommandResult host,
			BaseCmdHandler handler, Bundle cmdData,boolean showProgress) {
		try {
			Log("ALTAppMgr", "startServiceCmd:Start");
			CommandAsyncTask task = new CommandAsyncTask(host, handler,command, cmdData,showProgress);
			task.execute();
		} catch (Exception ex) {
			Log("ALTAppMgr", "startServiceCmd:" + ex.getMessage());
		}
	}

	public void startServiceCmdSilent(int command, IServiceCommandResult host,
			BaseCmdHandler handler, Bundle cmdData) {
		try {
			Log("ALTAppMgr", "startServiceCmd:Start");
			CommandAsyncTask task = new CommandAsyncTask(host, handler,
					command, cmdData, false);
			task.execute();
		} catch (Exception ex) {
			Log("ALTAppMgr", "startServiceCmd:" + ex.getMessage());
		}
	}

	public void Log(String section, String logMsg) {
		Log.i(ALTPTCMgr.TAG_DEF, section + " :: " + logMsg);
	}

	public void Log(String section, String logMsg, String tag) {
		Log.d(tag, section + " :: " + logMsg);
	}

	public void cleanCacheLocal(Context context) {
		try {			
//			context.deleteDatabase("webview.db");
//			context.deleteDatabase("webviewCache.db");			    
			File dir = context.getCacheDir();
			Log.e("trimCache weight: ", String.valueOf(dir.getTotalSpace()));
			if (dir != null && dir.isDirectory()) {
				Log.i("CleanCache", "Started");
				deleteDir(dir);			
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	//clear cache
	public boolean deleteDir(File dir) {
		try {
			if (dir != null && dir.isDirectory()) {
				String[] children = dir.list();
				for (int i = 0; i < children.length; i++) {
					boolean success = deleteDir(new File(dir, children[i]));
					if (!success) {
						return false;
					}else{
						Log.i("CleanCache", "success"+(i+1));					
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// The directory is now empty so delete it
		return dir.delete();
	}
	private UserLogInfo mUserLogInfo;
	public UserLogInfo getUserLogInfoModel() {
		if (mUserLogInfo == null) {
			mUserLogInfo = new UserLogInfo();
		}
		return mUserLogInfo;
	}
}
